<?php
namespace app\api\controller;

use think\Controller;
use think\Db;

class CalProfit extends controller{
    public function index(){
		//计算日收益
		//$fos_price = db('config')->where('name', 'fos_price')->value("value");
		$fos_price = 2000;
		$rule = db('rule')->order("id")->select();
		$rules = [];
		foreach($rule as $itm){
			$rules[$itm['level']] = $itm['earning'];
		}
        $users = db('users')->where('level>0')->select();
		foreach($users as $itm){
			//FOS是否增加
			/*$tmp = db('buy_list')->where('m_id='.$itm['id'].' AND status=2 AND twice_pass_time>="'.date("Y-m-d H:i:s", strtotime("-24 hours")).'"')->field('count(count) as all')->find();
			if($tmp['all']){
			    db('users')->where('id', $itm['id'])->setInc('coin', $tmp['all']);
			    db('users')->where('id', $itm['id'])->setDec('freeze_fos', $tmp['all']);
			}*/
			
			$fos_count = db('buy_list')->where(['m_id'=>$itm['id'], 'status'=>2, 'is_end'=>0])->sum("count");
		    $this->assign("amount", $fos_count);
		
			$fos = $fos_count*$fos_price;
			$earning = $rules["F".$itm['level']];
			$worth = round($fos * $earning/100, 4);
			//更改会员零钱包			
			Db::startTrans();
			try{ 
			    db("users")->where('id', $itm['id'])->setInc("money", $worth);
				$map['m_id'] = $itm['id'];
				$map['money'] = $worth;
				$map['add_time'] = date("Y-m-d H:i:s");
				$map['memo'] = "日收益(".$rules["F".$itm['level']]."%)";
				$map['type'] = 3;
				$map['old_money'] = $itm['money'];
				$map['new_money'] = $itm['money']+$worth;
				db("log")->insert($map);
			    Db::commit(); 
			}catch(\Exception $e){
				Db::rollback();
			}
		}
		
		//7天没有购买解除推广关系
		/*$fos_out_time = db('config')->where('name', 'fos_out_time')->value("value");
		$users = db('users')->where('level=0')->select();
		foreach($users as $itm){
			if($itm['reg_time'] < date("Y-m-d H:i:s", strtotime("-".$fos_out_time." hours"))){
				db("users")->where("id", $itm['id'])->update(['parent_id'=>"", 'f_p_ids'=>'']);
			}
		}*/
    }
	
	
	public function cal_fos_out()}{
		$rows = db('buy_list')->where('status=2 AND is_end=0')->select();
		foreach($rows as $itm){
			if($itm['twice_pass_time'] >= date('Y-m-d H:i:s', strtotime('-7 days'))){
				db('buy_list')->where('id', $itm['id'])->update(['is_end'=>1]);
				db('users')->where('id', $itm['m_id'])->setInc('money', $itm['count']*2000);
			}
		}
	}
}
